package com.aifast.core.view;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aifast.common.annotations.AiIdempotent;
import com.aifast.common.base.R;
import com.aifast.common.cache.util.RedisUtil;
import com.aifast.common.global.Const;
import com.aifast.common.util.AiUtil;
import com.aifast.system.sys.entity.UserInfo;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Author fujian
 * @since 2022/1/26 16:53
 */
public class AiIdempotentInterceptor implements HandlerInterceptor {

    private final static String s1 = "操作过快，请";
    private final static String s2 = "秒后再进行操作！";
    private final static List<String> urls = AiUtil.getExcludePathPatterns();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        AiIdempotent annotation = method.getAnnotation(AiIdempotent.class);
        if(ObjectUtil.isNull(annotation)){
            return true;
        }

        String uri = request.getRequestURI();
        if(urls.contains(uri)){
            return true;
        }
        String key = StrUtil.join(Const.SYMBOL_COLON,"idempotent", UserInfo.get().getUserId(),uri);
        if(RedisUtil.exists(key)){
            String msg = StrUtil.join(Const.EMPTY,s1,annotation.time(),s2);
            AiUtil.writeReturnJson(response, JSONUtil.toJsonStr(R.ERROR(msg)));
            return false;
        }
        RedisUtil.set(key,key,annotation.time());
        return true;
    }

}
